Getting A List of Contents 2

Latest update: July 2013

We will show the another way how to get a list of contents stored on the FlashAir. In this tutorial, we will use command.cgi to get the content list instead HTML embedding we used in Getting A List of Contents 1.

The list is embedded as a JavaScript part in a HTML file sent from FlashAir. To make it visible on screen, we need to generate another HTML document from the list by another JavaScript program.
In this tutorial, we will use jQuery to reduce the lines of code.

Preparation

We need jQuery as well as Getting A List of Contents 1 does. Please download it from the site and save it at /SD_WLAN/js/jquery.js on the FlashAir.

Creating View Layout

First, we make a HTML which is a main contents of the Browser Utility. It is very similar to the file created in Getting A List of Contents 1, but there is not script section in this tutorial.

Except that difference, the HTML file will also do two improtant things: 1) loading external JavaScript file, and 2) preparing <div> tag as a place holder for the JavaScript program to make visual elements shown on screen.

We must save the HTML file as a /SD_WLAN/List.htm on the FlashAir card.

/SD_WLAN/List.htm

<!doctype html>
<html>
<head>
<title>FlashAir</title>
<meta charset="UTF-8">
<script type="text/javascript" src="/SD_WLAN/js/jquery.js"></script>
<script type="text/javascript" src="/SD_WLAN/js/main.js"></script>
</head>
<body>
<div id="header">
<h1>header</h1>
</div>
<hr>
<div id="list">
</div>
<hr>
<div id="footer">
footer
</div>
</body>
</html>
  • Lines 6,7:
    This code loads jquery.js and main.js. main.js will be created next section.
  • Line 14:
    This code creates div tag having a value list for an attribute id. In following section, we will insert HTML elements for the content list here.

Generating HTML elements

We will create a JavaScript program which gets the content list and insert HTML elements into the HTML file we created before.

This contains two major routines: 1) getFileList(dir) issues CGI command to get the content list, and 2) showFileList(path) generates HTML elements from the content list returned.

We will reuse the helper functions created in Getting A List of Contents 1. In this tutorial, we will not use isV1(wlansd) since the format of the content list by CGI command is same between the firmware 1.00s' and 2.00s'.

Save the program as a /SD_WLAN/hjs/main.js on the FlashAir.

/SD_WLAN/js/main.js

// JavaScript Document

// Judge the card is V1 or V2.
function isV1(wlansd) {
    if ( wlansd.length == undefined || wlansd.length == 0 ) {
        // List is empty so the card version is not detectable. Assumes as V2.
        return false;
    } else if ( wlansd[0].length != undefined ) {
        // Each row in the list is array. V1.
        return true;
    } else {
        // Otherwise V2.
        return false;
    }
}
// Convert data format from V1 to V2.
function convertFileList() {
    for (var i = 0; i < wlansd.length; i++) {
        var elements = wlansd[i].split(",");
        wlansd[i] = new Array();
        wlansd[i]["r_uri"] = elements[0];
        wlansd[i]["fname"] = elements[1];
        wlansd[i]["fsize"] = Number(elements[2]);
        wlansd[i]["attr"]  = Number(elements[3]);
        wlansd[i]["fdate"] = Number(elements[4]);
        wlansd[i]["ftime"] = Number(elements[5]);
    }
}
// Callback Function for sort()
function cmptime(a, b) {
    if( a["fdate"] == b["fdate"] ) {
        return a["ftime"] - b["ftime"];
    }else{
        return a["fdate"] - b["fdate"];
    }
}
// Show file list
function showFileList(path) {
    // Clear box.
    $("#list").html('');
    // Output a link to the parent directory if it is not the root directory.
    if( path != "/" ) {
        $("#list").append(
            $("<div></div>").append(
                $('<a href="javascript:void(0)" class="dir">..</a>')
            )
        );
    }
    $.each(wlansd, function() {
        var file = this;
        // Skip hidden file.
        if ( file["attr"] & 0x02 ) {
            return;
        }
        // Make a link to directories and files.
        var filelink = $('<a href="javascript:void(0)"></a>');
        var caption = file["fname"];
        var fileobj = $("<div></div>");
        if ( file["attr"] & 0x10 ) {
            filelink.addClass("dir");
        } else {
            filelink.addClass("file").attr('href', file["r_uri"] + '/' + file["fname"]).attr("target","_blank");
        }
        // Append a file entry or directory to the end of the list.
        $("#list").append(
            fileobj.append(
                filelink.append(
                    caption
                )
            )
        );
    });     
}
//Making Path
function makePath(dir) {
    var arrPath = currentPath.split('/');
    if ( currentPath == "/" ) {
        arrPath.pop();
    }
    if ( dir == ".." ) {
        // Go to parent directory. Remove last fragment.
        arrPath.pop();
    } else if ( dir != "" && dir != "." ) {
        // Go to child directory. Append dir to the current path.
        arrPath.push(dir);
    }
    if ( arrPath.length == 1 ) {
        arrPath.push("");
    }
    return arrPath.join("/");
}
// Get file list
function getFileList(dir) {
    // Make a path to show next.
    var nextPath = makePath(dir);
    // Make URL for CGI. (DIR must not end with '/' except if it is the root.)
    var url = "/command.cgi?op=100&DIR=" + nextPath;
    // Issue CGI command.
    $.get(url, function(data) {
       // Save the current path.
        currentPath = nextPath;
        // Split lines by new line characters.
        wlansd = data.split(/\n/g);
        // Ignore the first line (title) and last line (blank).
        wlansd.shift();
        wlansd.pop();
        // Convert to V2 format.
        convertFileList(wlansd);
        // Sort by date and time.
        wlansd.sort(cmptime);

        // Show
        showFileList(currentPath);
    });
}
//Document Ready
$(function() {
    // Iniialize global variables.
    currentPath = location.pathname;
    wlansd = new Array();
    // Show the root directory.
    getFileList('');
    // Register onClick handler for <a class="dir">
    $(document).on("click","a.dir",function() {
        getFileList(this.text);
    }); 
});
  • Lines 38-73:
    showFileList(path) function generates an anchor ( <a>) and a division ( <div>) for each items in the content list, and append them to the place identified by list id, where has been prepared in the HTML in the previous section. Generated elements will be very similar to that of Getting A List of Contents 1, however, the function in this tutorial set the hyperlink as javascript:void(0) to avoid screen transition.
  • Lines 75-91:
    makePath(dir) function generates an aboslute path used for a CGI parameter. In order to successfully generate the CGI command URL, '/' should not be included at the end of the DIR parameter except the directory is the root.
  • Lines 93-115:
    getFileList() is the key function for this app. It takes the desired directory as an argument. This function gets the content list from the FlashAir card when the page is intially loaded or the directory link is clicked. At line 99, $.get is used to send the CGI command. We will code what to do for the retured data in the callback function ( function(data) {...}). It is because sending CGI command is executed in background. At line 113, we will show the returned data on screen.
  • Lines 117-127:
    This is a Document Ready function which will be automatically executed when the browser has completed loading this program. At line 119, we will initialize the current path from the URL of this page. At line 120, we will initialize an array to contain the content list. At lines from 124, the getFileList() function is bound to a click event. The click event constructs the content list using the getFileList() function, which uses the hyperlink text as an argument.

Result

Save the program on the FlashAir, and open your web browser on your PC or smartphone connected to the FlashAir, to check how the content list is shown.
You will see like a following screen shot.

This example is the case we show /DCIM/100__TSB. Note that the URL is not moved from flashair because Updating the content list on changing the current directory is done by CGI and JavaScript instead of screen transition.

Browser Utility Tutorial 3 Result

Sample Code

web_tutorial_03.zip (4KB)

All sample code on this page is licensed under BSD 2-Clause License